package com.study.system;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Netty的服务器
 */
public class NettyServer {

    public static final int PORT = 6668;
    public void start(){
        System.out.println("Netty服务器启动了！");
        //创建线程组 用于接受客户端
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //创建线程组 用于读写客户端
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            //创建服务器启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //配置线程组
            bootstrap.group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG, 1024) //设置等待队列
                    .channel(NioServerSocketChannel.class)       //设置通道类型
                    .childHandler(new ChannelInitializer<SocketChannel>() { //设置初始化器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //配置管道
                            socketChannel.pipeline()
                                    .addLast(new StringEncoder()) //添加字符串编码器
                                    .addLast(new StringDecoder()) //添加字符串解码器
                                    .addLast(new NettyServerHandler()); //添加自定义处理器
                        }
                    });
            //绑定服务器的特定端口
            ChannelFuture sync = bootstrap.bind("127.0.0.1", PORT).sync();
            //处理完后关闭连接
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyServer().start();
    }
}